<template>
  <el-popover placement="bottom" trigger="click" :width="360">
    <template #reference>
      <el-input v-model="search" size="mini" placeholder="过滤列名"></el-input>
    </template>
    <el-checkbox
      :indeterminate="isIndeterminate"
      v-model="isCheckedAll"
      @change="handleCheckAllChange"
      >全选</el-checkbox
    >
    <el-checkbox-group v-model="checkedItems" @change="refresh">
      <el-checkbox
        class="checkbox-item"
        v-for="item in visible"
        :checked="item.checked"
        :label="item.label"
        :key="item.value"
        >{{ item.label }}</el-checkbox
      >
    </el-checkbox-group>
  </el-popover>
</template>
<script>
export default {
  name: "FilterColumns",
  props: ["data"],
  emits: ["visibleColumns"],
  data() {
    return {
      isCheckedAll: true,
      checkedItems: [],
      isIndeterminate: false,
      search: "",
    };
  },
  methods: {
    handleCheckAllChange(val) {
      this.checkedItems = val ? this.data.map(({ value }) => value) : [];
      this.refresh();
    },
    refresh() {
      this.isCheckedAll = this.checkedItems.length === this.data.length;
      this.isIndeterminate = !this.isCheckedAll && !!this.checkedItems.length;
      this.$emit("visibleColumns", this.checkedItems.slice());
    },
  },
  computed: {
    visible() {
      return this.data.filter(({ value }) => {
        const case1 = value.indexOf(this.search) !== -1;
        const case2 = (this.search ?? "").indexOf(value) !== -1;
        return case1 || case2;
      });
    },
  },
};
</script>
<style scoped>
.checkbox-item {
  min-width: 150px;
}
</style>
